<?php
class SearchController extends AppController {
	public $helpers = array (
			'Html',
			'Form',
			'Session' 
	);
	private function escaseSQL($str) {
		if (! $str) {
			return null;
		}
		$str = str_replace ( '%', '\%', $str );
		$str = str_replace ( '_', '\_', $str );
		return $str;
	}
	public function searchtitle() {
		if (! isset ( $_GET ['condition'] )) {
			$this->Session->setFlash ( 'Please input search condition!', 'default', array (
					'class' => 'alert alert-danger' 
			) );
			return;
		} else {
			$condition = $_GET ['condition'];
			$condition = $this->escaseSQL ( $condition );
			$this->Session->write ( 'searchTitle', $condition );
		}
		// print_r($condition);
		// App::import('Sanitize');
		// App::uses('Sanitize', 'Utility');
		
		// print_r($condition);exit;
		$this->loadModel ( 'Post' );
		
		$numRow = $this->Post->find ( 'count', array (
				'conditions' => array (
						'Post.title LIKE' => '%' . $condition . '%' 
				) 
		) );
		
		if ($numRow < 1) {
			$this->Session->setFlash ( 'No data found!', 'default', array (
					'class' => 'alert alert-danger' 
			) );
			return;
		} else {
			$posts = $this->Post->find ( 'all', array (
					'conditions' => array (
							'Post.title LIKE' => '%' . $condition . '%' 
					),
					'order' => array (
							'Post.created DESC' 
					),
					'limit' => 10 
			) );
			
			// Load model Admin
			$this->loadModel ( 'User' );
			
			// Load model Comment
			$this->loadModel ( 'Comment' );
			
			// prepair data
			foreach ( $posts as $key => $post ) {
				
				// get review Text to show at homepage
				$textBody = $post ['Post'] ['body'];
				$bodyS = $this->reviewText ( 1000, $textBody );
				$posts [$key] ['Post'] ['body'] = $bodyS;
				
				// get admin username
				$author = $this->User->find ( 'first', array (
						'conditions' => array (
								'User.ID' => $post ['Post'] ['user_id'] 
						) 
				) );
				$posts [$key] ['Post'] ['username'] = $author ['User'] ['username'];
				
				// get number of comment
				$numComment = $this->Comment->find ( 'count', array (
						'conditions' => array (
								'Comment.post_id' => $post ['Post'] ['id'] 
						) 
				) );
				$posts [$key] ['Post'] ['numComment'] = $numComment;
				
				// created datetime format
				$formatDate = "F j, o";
				$created = $post ['Post'] ['created'];
				$posts [$key] ['Post'] ['created'] = date ( $formatDate, strtotime ( "$created" ) );
				
				// check thumbnail
				$thumbnail = trim ( $post ['Post'] ['thumbnail'] );
				if (empty ( $thumbnail )) {
					$posts [$key] ['Post'] ['thumbnail'] = "/images/no-photo.jpg";
				}
			}
			
			// hungdv get all sidebar list
			
			$this->set ( 'posts', $posts );
			$this->Session->setFlash ( 'Found ' . $numRow . ' results!', 'default', array (
					'class' => 'alert alert-success' 
			) );
		}
	}
	public function getmore() {
		// Set layout is empty
		$this->layout = "";
		if ($this->Session->check ( 'searchTitle' )) {
			// Load model Post
			$this->loadModel ( 'Post' );
			
			// get position of list post to countinues loading - ThanhLD1
			if (isset ( $_POST ['start'] ) && ( int ) ($_POST ['start'])) {
				$start = $_POST ['start'];
			} else {
				$start = 10;
			}
			
			$condition = $this->Session->read ( 'searchTitle' );
			// get more data start at current data on homepage index.ctp
			$posts = $this->Post->find ( 'all', array (
					'conditions' => array (
							'Post.title LIKE' => '%' . $condition . '%' 
					),
					'order' => array (
							'Post.created DESC' 
					),
					'offset' => $start,
					'limit' => 10 
			) );
			
			// if no have data in database of post table or have error occur
			if (! $posts) {
				throw new NotFoundException ( __ ( 'No data found!' ) );
			}
			
			// Load model Admin
			$this->loadModel ( 'User' );
			
			// Load model Comment
			$this->loadModel ( 'Comment' );
			
			// prepair data
			foreach ( $posts as $key => $post ) {
				
				// get review Text to show at homepage
				$textBody = $post ['Post'] ['body'];
				$bodyS = $this->reviewText ( 1000, $textBody );
				$posts [$key] ['Post'] ['body'] = $bodyS;
				
				// get admin username
				$author = $this->User->find ( 'first', array (
						'conditions' => array (
								'User.ID' => $post ['Post'] ['user_id'] 
						) 
				) );
				$posts [$key] ['Post'] ['username'] = $author ['User'] ['username'];
				
				// get number of comment
				$numComment = $this->Comment->find ( 'count', array (
						'conditions' => array (
								'Comment.post_id' => $post ['Post'] ['id'] 
						) 
				) );
				$posts [$key] ['Post'] ['numComment'] = $numComment;
				
				// created datetime format
				$formatDate = "F j, o";
				$created = $post ['Post'] ['created'];
				$posts [$key] ['Post'] ['created'] = date ( $formatDate, strtotime ( "$created" ) );
			}
			
			// return value to append current data at homepage index.ctp
			$this->set ( 'posts', $posts );
		}
	}
	
	/*
	 * ThanhLD1 - review text This function return a string with maxlength had given to review at homepage
	 */
	// function get text to show review on home page - ThanhLD1
	private function reviewText($maxLength, $html) {
		if (! $html)
			return "";
			// remove all tag html - ThanhLD1
		$result = trim ( strip_tags ( $html ) );
		if (empty ( $result )) {
			$result = "<p style=\"color: red;\">SORRY! NO REVIEW TEXT!</p>";
		}
		// cut string with length is maxLength - ThanhLD1
		if (strlen ( $result ) > $maxLength) {
			$pos = strpos ( $result, ' ', $maxLength );
			$result = substr ( $result, 0, $pos );
			$result .= "....";
		}
		
		return $result;
	}
	public function searchAdvance() {
	}
	private function isInputedAdvanceSearchCondition() {
		if (! isset ( $_GET ['title'] ) && ! isset ( $_GET ['postuser'] ) && ! isset ( $_GET ['datecreatefrom'] ) && ! isset ( $_GET ['datecreateto'] )) {
			return false;
		} else {
			return true;
		}
	}
	private function getSearchTitle() {
		if (isset ( $_GET ['title'] )) {
			return $_GET ['title'];
		} else {
			return null;
		}
	}
	private function getSearchPostUser() {
		if (isset ( $_GET ['postuser'] )) {
			return $_GET ['postuser'];
		} else {
			return null;
		}
	}
	private function getSearchDateCreateFrom() {
		if (isset ( $_GET ['datecreatefrom'] )) {
			return $_GET ['datecreatefrom'];
		} else {
			return null;
		}
	}
	private function getSearchDateCreateTo() {
		if (isset ( $_GET ['datecreateto'] )) {
			return $_GET ['datecreateto'];
		} else {
			return null;
		}
	}
	private function generateListCondition($listCondition, $title, $dateCreateFrom, $dateCreateTo) {
		if ($title != null) {
			array_push ( $listCondition, "Post.title LIKE '%" . $this->escaseSQL ( $title ) . "%'" );
		}
		if ($dateCreateFrom != null) {
			array_push ( $listCondition, "Post.created >= '" . $dateCreateFrom . " 00:00:00'" );
		}
		if ($dateCreateTo != null) {
			array_push ( $listCondition, "Post.created <= '" . $dateCreateTo . " 23:59:59'" );
		}
		return $listCondition;
	}
	public function doAdvanceSearch() {
		if (! $this->isInputedAdvanceSearchCondition ()) {
			$this->Session->setFlash ( 'Please input at least 1 condition to search!', 'default', array (
					'class' => 'alert alert-danger' 
			) );
			return $this->render ( '/search/search_advance' );
		}
		
		$title = $this->getSearchTitle ();
		$postUser = $this->getSearchPostUser ();
		$dateCreateFrom = $this->getSearchDateCreateFrom ();
		$dateCreateTo = $this->getSearchDateCreateTo ();
		
		$listCondition = array ();
		
		// neu session search theo user post bai duoc set
		if ($postUser != null) {
			// tim user co username giong nhu session dieu kien search
			$this->loadModel ( 'User' );
			$checkUser = $this->User->find ( 'first', array (
					'conditions' => array (
							'User.username' => $postUser 
					) 
			) );
			
			// neu khong tim thay user co username theo dieu kien search
			if (! $checkUser) {
				// set thong bao khong tim thay du lieu va set bien danh dau $isNodata = true
				$this->Session->setFlash ( 'No data found!', 'default', array (
						'class' => 'alert alert-danger' 
				) );
				return;
			} else {
				array_push ( $listCondition, 'Post.user_id = ' . $checkUser ['User'] ['id'] );
			}
		}
		
		$listCondition = $this->generateListCondition ( $listCondition, $title, $dateCreateFrom, $dateCreateTo );
		
		if (count ( $listCondition ) < 1) {
			$this->Session->setFlash ( 'Please input at least 1 condition to search!', 'default', array (
					'class' => 'alert alert-danger' 
			) );
			return $this->render ( '/search/search_advance' );
		}
		
		$this->Session->write ( 'searchAdvanceListCondition', $listCondition );
		
		$this->loadModel ( 'Post' );
		// select so dong du lieu ung voi danh sach dieu kien search
		$numRow = $this->Post->find ( 'count', array (
				'conditions' => $listCondition 
		) );
		
		// neu so dong du lieu < 1
		if ($numRow < 1) {
			// set thong bao loi khong tim thay du lieu
			$this->Session->setFlash ( 'No data found!', 'default', array (
					'class' => 'alert alert-danger' 
			) );
			return;
			
			// neu so dong du lieu >=1
		} else {
			// set thong bao tim thay n dong du lieu
			// select va set bien $posts, danh sach cac bai post thoa dieu kien search
			$posts = $this->Post->find ( 'all', array (
					'conditions' => $listCondition,
					'limit' => 10,
					'order' => array (
							'Post.created DESC' 
					) 
			) );
			
			// Load model Admin
			$this->loadModel ( 'User' );
			
			// Load model Comment
			$this->loadModel ( 'Comment' );
			
			// prepair data
			foreach ( $posts as $key => $post ) {
				
				// get review Text to show at homepage
				$textBody = $post ['Post'] ['body'];
				$bodyS = $this->reviewText ( 1000, $textBody );
				$posts [$key] ['Post'] ['body'] = $bodyS;
				
				// get admin username
				$author = $this->User->find ( 'first', array (
						'conditions' => array (
								'User.ID' => $post ['Post'] ['user_id'] 
						) 
				) );
				$posts [$key] ['Post'] ['username'] = $author ['User'] ['username'];
				
				// get number of comment
				$numComment = $this->Comment->find ( 'count', array (
						'conditions' => array (
								'Comment.post_id' => $post ['Post'] ['id'] 
						) 
				) );
				$posts [$key] ['Post'] ['numComment'] = $numComment;
				
				// created datetime format
				$formatDate = "F j, o";
				$created = $post ['Post'] ['created'];
				$posts [$key] ['Post'] ['created'] = date ( $formatDate, strtotime ( "$created" ) );
				
				// check thumbnail
				$thumbnail = trim ( $post ['Post'] ['thumbnail'] );
				if (empty ( $thumbnail )) {
					$posts [$key] ['Post'] ['thumbnail'] = "/images/no-photo.jpg";
				}
			}
			
			$this->set ( 'posts', $posts );
			
			$this->Session->setFlash ( 'Found ' . $numRow . ' results!', 'default', array (
					'class' => 'alert alert-success' 
			) );
		}
	}
	public function getmoreAdvanceSearch() {
		// Set layout is empty
		$this->layout = "";
		if ($this->Session->check ( 'searchAdvanceListCondition' )) {
			// Load model Post
			$this->loadModel ( 'Post' );
			
			// get position of list post to countinues loading - ThanhLD1
			if (isset ( $_POST ['start'] ) && ( int ) ($_POST ['start'])) {
				$start = $_POST ['start'];
			} else {
				$start = 10;
			}
			
			$listCondition = $this->Session->read ( 'searchAdvanceListCondition' );
			// get more data start at current data on homepage index.ctp
			$posts = $this->Post->find ( 'all', array (
					'conditions' => $listCondition,
					'order' => array (
							'Post.created DESC' 
					),
					'offset' => $start,
					'limit' => 10 
			) );
			
			// if no have data in database of post table or have error occur
			if (! $posts) {
				throw new NotFoundException ( __ ( 'No data found!' ) );
			}
			
			// Load model Admin
			$this->loadModel ( 'User' );
			
			// Load model Comment
			$this->loadModel ( 'Comment' );
			
			// prepair data
			foreach ( $posts as $key => $post ) {
				
				// get review Text to show at homepage
				$textBody = $post ['Post'] ['body'];
				$bodyS = $this->reviewText ( 1000, $textBody );
				$posts [$key] ['Post'] ['body'] = $bodyS;
				
				// get admin username
				$author = $this->User->find ( 'first', array (
						'conditions' => array (
								'User.ID' => $post ['Post'] ['user_id'] 
						) 
				) );
				$posts [$key] ['Post'] ['username'] = $author ['User'] ['username'];
				
				// get number of comment
				$numComment = $this->Comment->find ( 'count', array (
						'conditions' => array (
								'Comment.post_id' => $post ['Post'] ['id'] 
						) 
				) );
				$posts [$key] ['Post'] ['numComment'] = $numComment;
				
				// created datetime format
				$formatDate = "F j, o";
				$created = $post ['Post'] ['created'];
				$posts [$key] ['Post'] ['created'] = date ( $formatDate, strtotime ( "$created" ) );
			}
			
			// return value to append current data at homepage index.ctp
			$this->set ( 'posts', $posts );
		}
	}
	public function beforeFilter() {
		parent::beforeFilter ();
		$this->Auth->allow();
	}
}
